/*
 * barrier.c
 *
 *  Created on: May 1, 2014
 *      Author: eran
 */

#include "uthread.h"
#include "barrier.h"


void barrier_init(struct barrier *bar, int num)
{
	bar->n = num;
	bar->counter = 0;
	bar->arrival = malloc(sizeof(struct binary_semaphore));
	bar->departure = malloc(sizeof(struct binary_semaphore));
	binary_semaphore_init(bar->arrival, 1);
	binary_semaphore_init(bar->departure, 0);
}

void barrier_pass(struct barrier *bar)
{
	binary_semaphore_down(bar->arrival);
	bar->counter++;
	if (bar->counter < bar->n)
		binary_semaphore_up(bar->arrival);
	else
		binary_semaphore_up(bar->departure);
	binary_semaphore_down(bar->departure);
	bar->counter--;
	if (bar->counter > 0)
		binary_semaphore_up(bar->departure);
	else
		binary_semaphore_up(bar->arrival);
}





